﻿using System;
using System.Windows.Forms;
using System.IO;
using System.Text;
using System.Collections.Generic;

namespace Vcf2Csv
{
    public partial class FmVcfCsv : Form
    {
        public FmVcfCsv()
        {
            InitializeComponent();
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            using (FolderBrowserDialog fb = new FolderBrowserDialog())
            {
                var path = this.txtPath.Text;

                if (!string.IsNullOrWhiteSpace(path)
                    && Directory.Exists(path))
                {
                    fb.SelectedPath = path;
                }

                if (fb.ShowDialog(this) == DialogResult.OK)
                {
                    this.txtPath.Text = fb.SelectedPath;
                }
            }
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void btnSubmit_Click(object sender, EventArgs e)
        {
            string path = this.txtPath.Text;
            
            this.lblStatusMessage.Text = "Processing";

            if (string.IsNullOrWhiteSpace(path)
                || !Directory.Exists(path))
                return;

            StringBuilder sb = new StringBuilder();

            IList<string> contactCards = Directory.GetFiles(path, "*.vcf", SearchOption.TopDirectoryOnly);

            if (contactCards == null
                || contactCards.Count <= 0)
                return;

            this.pbConversionState.Minimum = 0;
            this.pbConversionState.Maximum = contactCards.Count;

            IList<string> keywordsToSkip = new List<string> { "Begin", "End", "Version" };

            for (int index = 0; index < contactCards.Count; index++)
            {
                string vcf = contactCards[index];
                uint currentColumnCount = 0;

                using (FileStream stream = new FileStream(vcf, FileMode.Open))
                {
                    using (StreamReader sr = new StreamReader(stream))
                    {
                        var lineText = string.Empty;

                        do
                        {
                            lineText = sr.ReadLine();

                            if (string.IsNullOrWhiteSpace(lineText))
                                break;

                            IList<string> lineParts = lineText.Split(':');

                            bool skipIteration = lineParts.Count <= 0;

                            if (!skipIteration)
                            {
                                string keyword = lineParts[0];

                                for (int keyIndex = 0; keyIndex < keywordsToSkip.Count; keyIndex++)
                                {
                                    var currentKey = keywordsToSkip[keyIndex];

                                    if (string.Equals(currentKey, keyword, StringComparison.OrdinalIgnoreCase))
                                        skipIteration = true;
                                }
                            }

                            if (skipIteration)
                                continue;
                            else if (lineParts.Count > 1)
                            {
                                sb.Append(lineParts[1]);
                                sb.Append(", ");
                                currentColumnCount++;
                            }

                        } while (true);
                    }
                }
                if (currentColumnCount > 0)
                    sb.Append(Environment.NewLine);
                this.pbConversionState.Increment(1);
            }

            if (sb.Length > 0)
            {
                using (SaveFileDialog saveDialog = new SaveFileDialog())
                {
                    saveDialog.DefaultExt = "csv";
                    saveDialog.Filter = "CSV (*.csv)|*.csv";
                    if (saveDialog.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                    {
                        string fileName = saveDialog.FileName;

                        File.WriteAllText(fileName, sb.ToString(), System.Text.Encoding.UTF8); 
                    }
                }
                sb.Clear();
            }

            this.lblStatusMessage.Text = "Completed";

        }
    }
}
